package com.uduemc.biso.node.web.api.validator.impl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.uduemc.biso.node.web.api.validator.ProportionToFloat;

public class ProportionToFloatValid implements ConstraintValidator<ProportionToFloat, String> {

	@Override
	public void initialize(ProportionToFloat constraintAnnotation) {

	}

	/**
	 * 只能是100以内的有效浮点数，小数点后只能有2位
	 */
	@Override
	public boolean isValid(String proportion, ConstraintValidatorContext context) {
		if (proportion.equals("100") || proportion.equals("100.00")) {
			return true;
		}
		// 字符长度不能大于5
		if (proportion.length() > 5) {
			return false;
		}
		Float percentage = null;
		try {
			percentage = Float.valueOf(proportion);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		if (percentage == null) {
			return false;
		}
		if (percentage > 100f || percentage < -1) {
			return false;
		}
		return true;
	}

}
